<template>
  <div class="setmeal-page">
    <el-breadcrumb
      class="breadcrumb-margin"
      separator-class="el-icon-arrow-right"
    >
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>产品管理</el-breadcrumb-item>
      <el-breadcrumb-item>套餐列表</el-breadcrumb-item>
    </el-breadcrumb>

    <div class="setmeal-container">
      <el-card class="box-card setmeal-list">
        <div slot="header" class="header-container">
          <el-row :gutter="30" class="card-row">
            <el-col :span="11">
              <el-input
                placeholder="请输入套餐名称(空值默认查询所有套餐)"
                v-model="selectName"
                clearable
                class="input-with-select"
                @keyup.enter.native="
                  selectSetmeal(selectName, selectCategory, null, 1, 10)
                "
                @clear="selectSetmeal(null, selectCategory, null, 1, 10)"
              >
                <el-select
                  v-model="selectCategory"
                  slot="prepend"
                  placeholder="所有分类"
                  @change="
                    selectSetmeal(selectName, selectCategory, null, 1, 10)
                  "
                  style="width: 130px"
                >
                  <el-option label="所有分类" :value="null"> </el-option>
                  <el-option
                    v-for="item in categoryList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
                <template slot="append">
                  <el-button
                    icon="el-icon-search"
                    @click="
                      selectSetmeal(selectName, selectCategory, null, 1, 10)
                    "
                  ></el-button>
                </template>
              </el-input>
            </el-col>
            <el-col :span="4">
              <el-button type="success" @click="dialogAddVisible = true">
                <i class="el-icon-plus"></i> 添加套餐
              </el-button>
            </el-col>
            <el-col :span="4">
              <el-button
                type="danger"
                @click="deleteSetmeal(multipleSelection.map((item) => item.id))"
              >
                <i class="el-icon-delete"></i> 批量删除套餐
              </el-button>
            </el-col>
          </el-row>
        </div>

        <el-table
          :data="setmealList"
          style="width: 100%"
          border
          class="hospital-table"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-row :gutter="20" class="expanded-row">
                <el-col
                  :span="8"
                  v-for="item in props.row.products"
                  :key="item.id"
                >
                  <el-card class="product-card" shadow="hover">
                    <img :src="item.image" class="product-image" />
                    <div class="product-info">
                      <h3>{{ item.productName }}</h3>
                      <p>价格: {{ item.productPrice.toFixed(2) }}</p>
                      <p>数量: {{ item.copies }}</p>
                    </div>
                  </el-card>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column type="index" label="#" width="60"></el-table-column>
          <el-table-column label="套餐名称" prop="name" width="150"></el-table-column>
          <el-table-column prop="image" label="套餐图片" width="150">
            <template slot-scope="scope">
              <div class="avatar-container">
                <img :src="scope.row.image" class="avatar" />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="套餐价格" prop="price" width="150">
            <template slot-scope="scope">
              {{ calculateSetmealPrice(scope.row).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column
            label="套餐分类"
            prop="categoryName"
            width="150"
          ></el-table-column>
          <el-table-column
            label="详细描述"
            prop="description"
            width="230"
          ></el-table-column>
          <el-table-column label="修改时间" prop="updateTime" width="180"></el-table-column>
          <el-table-column prop="status" label="状态" width="80">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
                @change="updateStatus(scope.row.status, scope.row.id)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template slot-scope="slot">
              <el-tooltip
                effect="dark"
                content="修改"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  circle
                  @click="selectSetmealById(slot.row.id)"
                ></el-button>
              </el-tooltip>
              <el-tooltip
                effect="dark"
                content="删除"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="deleteSetmeal([slot.row.id])"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="currentPage"
            :page-size="pageSelect.pageSize"
            layout="prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </el-card>

      <el-dialog title="添加套餐" :visible.sync="dialogAddVisible" width="70%">
        <el-form
          :model="setmealForm"
          :rules="rules"
          ref="setmealForm"
          label-width="100px"
        >
          <!-- 基本信息 -->
          <el-form-item label="套餐名称" prop="name">
            <el-input v-model="setmealForm.name"></el-input>
          </el-form-item>
          <el-form-item label="套餐分类" prop="categoryId">
            <el-select
              v-model="setmealForm.categoryId"
              placeholder="请选择套餐分类"
            >
              <el-option
                v-for="item in categoryList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="套餐描述" prop="description">
            <el-input
              type="textarea"
              v-model="setmealForm.description"
            ></el-input>
          </el-form-item>

          <!-- 套餐图片上传 -->
          <el-form-item label="套餐图片" prop="image">
            <el-upload
              class="avatar-uploader"
              action="/api/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="setmealForm.image"
                :src="setmealForm.image"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>

          <!-- 产品选择 -->
          <el-form-item label="添加产品">
            <el-select
              v-model="selectedProductId"
              filterable
              remote
              reserve-keyword
              placeholder="请输入产品名称搜索"
              :remote-method="remoteSearch"
              :loading="loading"
            >
              <el-option
                v-for="item in products"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
            <el-button @click="addProduct" type="primary" icon="el-icon-plus"
              >添加</el-button
            >
          </el-form-item>

          <!-- 已选产品列表 -->
          <el-table :data="setmealForm.products" style="width: 100%">
            <el-table-column
              prop="productName"
              label="产品名称"
            ></el-table-column>
            <el-table-column prop="productPrice" label="单价"></el-table-column>
            <el-table-column label="数量">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.copies"
                  :min="1"
                  @change="calculateTotal"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  @click.native.prevent="deleteRow(scope.row.productId)"
                  type="text"
                  size="small"
                >
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 套餐总价 -->
          <el-form-item label="套餐总价">
            <span>{{ setmealForm.price }} 元</span>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeAndResetForm">取 消</el-button>
          <el-button type="primary" @click="submitForm(setmealForm)"
            >确 定</el-button
          >
        </div>
      </el-dialog>

      <el-dialog
        title="修改套餐"
        :visible.sync="dialogUpdateVisible"
        width="70%"
      >
        <el-form
          :model="setmealForm"
          :rules="rules"
          ref="setmealForm"
          label-width="100px"
        >
          <!-- 基本信息 -->
          <el-form-item label="套餐名称" prop="name">
            <el-input v-model="setmealForm.name"></el-input>
          </el-form-item>
          <el-form-item label="套餐分类" prop="categoryId">
            <el-select
              v-model="setmealForm.categoryId"
              placeholder="请选择套餐分类"
            >
              <el-option
                v-for="item in categoryList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="套餐描述" prop="description">
            <el-input
              type="textarea"
              v-model="setmealForm.description"
            ></el-input>
          </el-form-item>

          <!-- 套餐图片上传 -->
          <el-form-item label="套餐图片" prop="image">
            <el-upload
              class="avatar-uploader"
              action="/api/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="setmealForm.image"
                :src="setmealForm.image"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>

          <!-- 产品选择 -->
          <el-form-item label="添加产品">
            <el-select
              v-model="selectedProductId"
              filterable
              remote
              reserve-keyword
              placeholder="请输入产品名称搜索"
              :remote-method="remoteSearch"
              :loading="loading"
            >
              <el-option
                v-for="item in products"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
            <el-button @click="addProduct" type="primary" icon="el-icon-plus"
              >添加</el-button
            >
          </el-form-item>

          <!-- 已选产品列表 -->
          <el-table :data="setmealForm.products" style="width: 100%">
            <el-table-column
              prop="productName"
              label="产品名称"
            ></el-table-column>
            <el-table-column prop="productPrice" label="单价"></el-table-column>
            <el-table-column label="数量">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.copies"
                  :min="1"
                  @change="calculateTotal"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  @click.native.prevent="deleteRow(scope.row.productId)"
                  type="text"
                  size="small"
                >
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 套餐总价 -->
          <el-form-item label="套餐总价">
            <span>{{ setmealForm.price }} 元</span>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeAndResetForm">取 消</el-button>
          <el-button type="primary" @click="updateSetmeal(setmealForm)"
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      setmealList: [],
      pageSelect: {
        page: 1,
        pageSize: 10,
      },
      total: null,
      selectCategory: null,
      selectName: "",
      categoryList: [],
      dialogAddVisible: false,
      setmealForm: {
        name: "",
        categoryId: "",
        description: "",
        image: "",
        products: [],
        price: null,
        status: null,
      },
      setmealProduct: {
        id: null,
        setmealId: null,
        productId: null,
        productName: "",
        productPrice: null,
        copies: null,
      },
      rules: {
        name: [{ required: true, message: "请输入套餐名称", trigger: "blur" }],
        categoryId: [
          { required: true, message: "请选择套餐分类", trigger: "change" },
        ],
        image: [
          { required: true, message: "请上传套餐图片", trigger: "change" },
        ],
      },
      selectedProductId: null,
      products: [],
    };
  },
  computed: {
    selectedProduct() {
      return this.products.find((p) => p.id === this.selectedProductId);
    },
  },
  methods: {
    selectSetmeal(name, categoryId, status, page, pageSize) {
      this.$http
        .get("/webPage/setmeal/page", {
          params: {
            name: name,
            categoryId: categoryId,
            status: status,
            page: page,
            pageSize: pageSize,
          },
        })
        .then((res) => {
          if (res.data.code === 1) {
            this.setmealList = res.data.data.records;
            this.total = res.data.data.total;
          }
        });
    },
    calculateSetmealPrice(setmeal) {
      return setmeal.products.reduce((total, product) => {
        return total + product.productPrice * product.copies;
      }, 0);
    },
    remoteSearch(query) {
      if (query !== "") {
        this.loading = true;
        // 使用 query 调用后端 API
        this.$http
          .get("/webPage/product/remoteSearch", { params: { name: query } })
          .then((response) => {
            this.loading = false;
            this.products = response.data.data;
          })
          .catch((error) => {
            this.loading = false;
            console.error("搜索产品时出错:", error);
          });
      } else {
        this.products = [];
      }
    },
    addProduct() {
      if (!this.selectedProduct) return;
      const index = this.setmealForm.products.findIndex(
        (item) => item.productId === this.selectedProduct.id
      );
      if (index !== -1) {
        this.setmealForm.products[index].copies =
          this.setmealForm.products[index].copies + 1;
      } else {
        this.selectedProduct.copies = 1;
        this.setmealForm.products.push({
          id: null,
          setmealId: null,
          productId: this.selectedProduct.id,
          productName: this.selectedProduct.name,
          productPrice: this.selectedProduct.price,
          copies: this.selectedProduct.copies,
        });
      }
      this.calculateTotal();
      this.products = null;
      this.selectedProductId = null;
    },
    calculateTotal() {
      this.setmealForm.price = this.setmealForm.products.reduce(
        (total, product) => {
          return total + product.productPrice * product.copies;
        },
        0
      );
    },
    deleteRow(id) {
      const index = this.setmealForm.products.findIndex(
        (item) => item.productId === id
      );
      if (index !== -1) {
        this.setmealForm.products.splice(index, 1);
      }
      this.calculateTotal();
    },
    submitForm(setmealForm) {
      this.$http.post("/webPage/setmeal/add", setmealForm).then((res) => {
        if (res.data.code === 1) {
          this.$message.success("添加成功");

          this.selectSetmeal(null, null, null, 1, this.pageSelect.pageSize);
          this.closeAndResetForm(); // 关闭对话框并重置表单
        }
      });
    },
    closeAndResetForm() {
      this.dialogAddVisible = false;
      this.dialogUpdateVisible = false;
      this.$nextTick(() => {
        this.$refs.setmealForm.resetFields();
        this.setmealForm = {
          name: "",
          categoryId: "",
          description: "",
          image: "",
          products: [],
          price: null,
          status: null,
        };
        this.selectedProductId = null;
      });
    },
    selectSetmealById(id) {
      this.$http.get(`/webPage/setmeal/getById/${id}`).then((res) => {
        this.setmealForm = res.data.data;
        this.dialogUpdateVisible = true;
      });
    },
    updateSetmeal(setmealForm) {
      this.$http
        .put("/webPage/setmeal/update", {
          id: setmealForm.id,
          categoryId: setmealForm.categoryId,
          name: setmealForm.name,
          price: setmealForm.price,
          description: setmealForm.description,
          image: setmealForm.image,
          products: setmealForm.products,
        })
        .then((res) => {
          if (res.data.code === 1) {
            this.selectSetmeal(null, null, null, 1, this.pageSelect.pageSize);
            this.closeAndResetForm();
            this.$message.success("修改成功");
          }
        });
    },
    deleteSetmeal(ids) {
      this.$confirm("此操作将永久删除该套餐, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$http.delete(`/webPage/setmeal/delete?ids=${ids}`).then((res) => {
          if (res.data.code === 1) {
            this.selectSetmeal(null, null, null, 1, this.pageSelect.pageSize);
            this.$message.success("删除成功");
          }
        });
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    updateStatus(status,id){
      this.$http.post(`/webPage/setmeal/status/${status}?id=${id}`)
    },
    handleCurrentChange(val){
      this.selectSetmeal(null,null,null,val,this.pageSelect.pageSize)
    }
  },
  created() {
    this.selectSetmeal(
      null,
      null,
      null,
      this.pageSelect.page,
      this.pageSelect.pageSize
    );
    this.$http
      .get("/webPage/category/selectByType", {
        params: {
          type: 2,
        },
      })
      .then((res) => {
        this.categoryList = res.data.data;
      });
  },
};
</script>
<style lang="less" scoped>
.setmeal-page {
  padding: 20px;
  background-color: #f0f2f5;
   font-family: 'Arial', sans-serif;
}

.breadcrumb-margin {
  margin-bottom: 20px;
}

.setmeal-container {
  display: flex;
  justify-content: space-between;
}

.setmeal-list {
  flex: 1;
  margin-right: 20px;
}

.setmeal-sidebar {
  width: 300px;
}

.box-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0.1);
}

.header-container {
  background-color: #f6f8fa;
  padding: 15px;
  border-bottom: 1px solid #d1e8ff;
}

.card-row {
  display: flex;
  align-items: center;
  gap: 15px
}

.input-with-select {
  width: 100%;
 
}

.hospital-table {
  margin-top: 20px;
}
.hospital-table :deep(th) {
  background-color: #e6f3ff;
  color: #589aea;
  font-weight: bold;
  text-align: center;
}

.hospital-table :deep(td) {
  color: #727679;
  text-align: center;
}

.hospital-table :deep(.el-table__body tr:hover) {
  background-color: #c3e2fd !important; /* 更浅的浅蓝色背景 */
}
.hospital-table :deep(.el-table__body td:hover) {
  background-color: #7bc3f6 !important; /* 较深的浅蓝色背景 */
}
/* 解决鼠标切换行时悬浮效果不立即生效的问题 */
.hospital-table :deep(.el-table__row:hover td) {
  background-color: #c3e2fd !important; /* 确保鼠标悬停时整行生效 */
}
.hospital-table :deep(.el-table__row td:hover) {
  background-color: #7bc3f6 !important; /* 鼠标悬停在单元格上时单元格高亮 */
}
.expanded-row {
  padding: 20px;
  background-color: #f9f9f9;
}
.block {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.el-pagination {
  background-color: #f9fafc00; /* 分页区域背景 */
  padding: 10px 15px; /* 分页内边距 */
  border-radius: 6px; /* 圆角效果 */
}

.el-pagination :deep(.el-pager li) {
  font-size: 14px;
  color: #3a7fda; /* 使用专业蓝色 */
  margin: 0 5px;
}

.el-pagination :deep(.el-pager li.active) {
  background-color: #3a7fda;
  color: #fff;
}

.product-card {
  margin-bottom: 20px;
  border-radius: 10px;
  overflow: hidden;
  transition: all 0.3s ease;
  height: 100%;
  display: flex;
  flex-direction: column;
   box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.15);
}

.product-image {
  width: 100%;
  height: 150px;
  object-fit: cover;
}

.product-info {
  padding: 15px;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-info h3 {
  margin: 0 0 10px;
  color: #3a7fda;
  font-size: 16px;
}

.product-info p {
  margin: 5px 0;
  color: #2ba1ef;
  font-size: 14px;
}

.avatar-container {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 auto;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.block {
  margin-top: 20px;
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .setmeal-container {
    flex-direction: column;
  }

  .setmeal-list {
    margin-right: 0;
    margin-bottom: 20px;
  }

  .setmeal-sidebar {
    width: 100%;
  }
}

@media (max-width: 768px) {
  .card-row {
    flex-direction: column;
  }

  .card-row > * {
    margin-bottom: 10px;
  }

  .expanded-row {
    padding: 10px;
  }

  .product-card {
    margin-bottom: 10px;
  }

  .product-image {
    height: 120px;
  }

  .product-info {
    padding: 10px;
  }

  .product-info h3 {
    font-size: 14px;
  }

  .product-info p {
    font-size: 12px;
  }
}
</style>


